package com.chat.handler;

import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.URL;


/**
 * @author kewei
 * 对HTTP的支持
 * 处理服务端分发请求的逻辑
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    /**
     * 获取class路径
     */
    private URL baseURL = HttpServerHandler.class.getResource("");

    private final String webroot = "webroot";

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("Client异常:" + channel.remoteAddress());
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        String uri = "";
        RandomAccessFile file = null;
        try {
            uri = request.uri();
            String page = "/".equals(uri) ? "chat.html" : uri;
            file = new RandomAccessFile(getResource(page), "r");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        HttpResponse response = new DefaultHttpResponse(request.protocolVersion(), HttpResponseStatus.OK);
        String contentType = null;
        if (uri.endsWith(".css")) {
            contentType = "text/css;";
        } else if (uri.endsWith(".js")) {
            contentType = "text/javascript;";
        } else if (uri.toLowerCase().matches(".*\\.(jpg|png|gif)$")) {
            contentType = String.format("image/%s", uri.substring(uri.lastIndexOf(".")));
        } else {
            contentType = "text/html;";
        }
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType + "charset=utf-8;");
        boolean keepAlive = HttpHeaderUtil.isKeepAlive(request);
        if (keepAlive) {
            response.headers().setLong(HttpHeaderNames.CONTENT_LENGTH, file.length());
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        ctx.write(response);
        ctx.write(new DefaultFileRegion(file.getChannel(), 0, file.length()));
        ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        if (!keepAlive) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
        file.close();
    }

    public File getResource(String fileName) throws Exception {
        String basePath = baseURL.toURI().toString();
        int start = basePath.indexOf("classes/");
        basePath = String.format("%s/classes/", basePath.substring(0, start).replaceAll("/+", "/"));
        String path = String.format("%s%s/%s", basePath, webroot, fileName);
        path = !path.contains("file:") ? path : path.substring(5);
        path = path.replaceAll("//", "/");
        return new File(path);
    }


}
